import fs from "fs/promises";
import prisma from "@/src/db/db";
import { revalidatePath } from "next/cache";
import { notFound } from "next/navigation";

import { NextResponse } from "next/server";

export const GET = async () => {
  const res = await prisma.product.findMany({
    select: {
      id: true,
      name: true,
      priceInCents: true,
      isAvailableForPurchase: true,
      createAt: true,
      _count: { select: { orders: true } },
    },
    orderBy: { createAt: "desc" },
  });
  return NextResponse.json(res);
};

export const POST = async (req) => {
  let data = await req.json();
  const res = await prisma.product.create({ data });
  revalidatePath("/products");
  revalidatePath("/");
  return NextResponse.json(res);
};

export const PUT = async (req) => {
  let { id, isAvailableForPurchase } = await req.json();
  const res = await prisma.product.update({
    where: { id },
    data: { isAvailableForPurchase },
  });
  return NextResponse.json(res);
};

export const DELETE = async (req) => {
  // 获取 ?id=1 中的 id
  const { searchParams } = new URL(req.url);
  const id = searchParams.get("id");
  const product = await prisma.product.delete({
    where: { id },
  });
  if (product == null) {
    return notFound();
  }
  // 删除产品时，同时删除文件
  await Promise.all([
    fs.unlink(product.filePath),
    fs.unlink(product.imagePath),
  ]);
  return NextResponse.json(product);
};
